package com.renchunlin.logindemo01.utils

import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl
import java.util.*
import kotlin.collections.ArrayList


/*
 * class title: 特殊的自动管理Cookies
 * Author by RenChunLin, Email 18957806320@163.com, Date on 2021/6/23.
 * PS: Not easy to write code, please indicate.
 */
class CookiesManager : CookieJar {

    //保存每个url的cookie
    private var cookieStore: HashMap<HttpUrl, List<Cookie>> = HashMap()

    //上一个请求url
    private lateinit var url: HttpUrl

    override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
        //保存链接的cookie
        cookieStore[url] = cookies
        //保存上一次的url，供给下一次cookie的提取。
        this.url = url
    }

    override fun loadForRequest(url: HttpUrl): List<Cookie> {
        //加载上一个链接的cookie
        return cookieStore[url] ?: ArrayList()
    }

}